//
//  ShopController.m
//  FreeTrip
//
//  Created by 352324497@qq.com on 15/11/25.
//  Copyright © 2015年 邓芮. All rights reserved.
//

#import "ShopController.h"
#import "ShopHeaderView.h"
#import "ShopTableViewCell.h"
#import "ShopFooterView.h"
#import "ShopTotalController.h"
#import "TravelEssentialsController.h"
#import "FunTicketController.h"
#import "TrafficController.h"
#import "LocalPlansController.h"
#import "ShopDetailController.h"
@interface ShopController ()

@property (nonatomic, strong)NSMutableArray *modelArray;
@property (nonatomic, assign) NSInteger moreNum;//加载更多
@property (nonatomic, strong) NSData *tempData;
@end

@implementation ShopController
- (NSMutableArray *)modelArray
{
    if (!_modelArray )
    {
        self.modelArray = [NSMutableArray array];
    }
    return _modelArray;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.separatorStyle = NO;
    self.navigationItem.title = [NSString stringWithFormat:@"%@商品", self.name];
    self.moreNum = 1;
    
    [self.tableView registerClass:[ShopHeaderView class] forHeaderFooterViewReuseIdentifier:@"header"];
    [self.tableView registerClass:[ShopFooterView class] forHeaderFooterViewReuseIdentifier:@"footer"];
    
   
    
       
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        self.moreNum = self.moreNum + 1;
         [self netRequestForShopWithUrl:[NSString stringWithFormat:@"http://chanyouji.com/api/items.json?destination_id=%ld&featured=true&page=%ld",(long)self.Id,(long)self.moreNum]];
        
        [self.tableView.mj_footer endRefreshing];
    }];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        [self netRequestForShopWithUrl:[NSString stringWithFormat:@"http://chanyouji.com/api/items.json?destination_id=%ld&featured=true&page=%ld",(long)self.Id,(long)self.moreNum]];
        [self.tableView.mj_header endRefreshing];
    }];
    [self.tableView.mj_header beginRefreshing];


}

#pragma mark ---shopRequest00请求---
//http://chanyouji.com/api/items.json?destination_id=71&page=1
- (void)netRequestForShopWithUrl:(NSString *)url
{
   
    
    [[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
      {
          if ([self.tempData isEqual:data])
          {
              self.tableView.bounces = NO;
              self.tableView.showsVerticalScrollIndicator = NO;
              return ;
          }
          self.tempData = data;
          
          if (data == nil)
          {
              NSLog(@"数据请求失败");
              return ;
          }
          
          NSDictionary *zomDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
          
          for (NSDictionary *secDic in zomDic[@"items"])
          {
              ShopModel *model = [[ShopModel alloc] init];
              [model setValuesForKeysWithDictionary:secDic];
              [_modelArray addObject:model];
              
          }
          
          dispatch_async(dispatch_get_main_queue(), ^{
              [self.tableView reloadData];
              if (self.modelArray.count == 0)
              {
                  UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, KScreenHeight / 2 - 50 * KScreenWidth / 375, KScreenWidth, 50 * KScreenWidth / 375)];
                  label.text = @"空空如也";
                  label.font = [UIFont systemFontOfSize:40 * KScreenWidth / 375];
                  label.textColor = [UIColor lightGrayColor];
                  label.textAlignment = NSTextAlignmentCenter;
                  [self.tableView addSubview:label];
              }
          });
      }] resume];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArray.count;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    ShopHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    [headerView.travelEssentialsButton addTarget:self action:@selector(travelEssentialsButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [headerView.funTicketButton addTarget:self action:@selector(funTicketButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [headerView.trafficButton addTarget:self action:@selector(trafficButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [headerView.localPlansButton addTarget:self action:@selector(localPlansButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    return headerView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return [ShopHeaderView heightForHeader];
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    ShopFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"footer"];
    [footerView.footerButton addTarget:self action:@selector(footerButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    return footerView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 40 * KScreenWidth / 375;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [ShopTableViewCell heightForCell];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ShopTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil)
    {
        cell = [[ShopTableViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"cell"];
    }
    cell.layer.borderColor = [UIColor lightGrayColor].CGColor;
    cell.layer.borderWidth = 0.5;
    ShopModel *model = self.modelArray[indexPath.row];
    cell.model = model;
    return cell;
}

#pragma mark - 点击 cell 事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ShopModel *model = self.modelArray[indexPath.row];
    ShopDetailController *shopDetailViewVc = [[ShopDetailController alloc]initWithStyle:(UITableViewStyleGrouped)];
//    NSLog(@"===== %ld", model.Id);
    shopDetailViewVc.name = model.name;
    shopDetailViewVc.Id = model.Id;
    shopDetailViewVc.model = (ShopDetailHeaderModel *)model;
    [self.navigationController pushViewController:shopDetailViewVc animated:YES];
}
#pragma mark - 出行必备点击方法
-(void)travelEssentialsButtonAction:(ShopButton *)travelEssentialsButton
{
//    ShopTableViewCell *cell = (ShopTableViewCell *)travelEssentialsButton.superview.superview;
//    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    TravelEssentialsController *travelViewVc = [[TravelEssentialsController alloc]initWithStyle:(UITableViewStylePlain)];
    travelViewVc.Id = self.Id;
    [self.navigationController pushViewController:travelViewVc animated:YES];
}

#pragma mark - 门票玩乐点击方法
-(void)funTicketButtonAction:(ShopButton *)funTicketButton
{
    FunTicketController *funTicketViewVc = [[FunTicketController alloc]initWithStyle:(UITableViewStylePlain)];
    funTicketViewVc.Id = self.Id;
    [self.navigationController pushViewController:funTicketViewVc animated:YES];
}

#pragma mark - 交通接驳点击方法
-(void)trafficButtonAction:(ShopButton *)trafficButton
{
    TrafficController *trafficViewVc = [[TrafficController alloc]initWithStyle:(UITableViewStylePlain)];
    trafficViewVc.Id = self.Id;
    [self.navigationController pushViewController:trafficViewVc animated:YES];
}

#pragma mark - 当地行程点击方法
-(void)localPlansButtonAction:(ShopButton *)localPlansButton
{
    LocalPlansController *localPlabsViewVc = [[LocalPlansController alloc]initWithStyle:(UITableViewStylePlain)];
    localPlabsViewVc.Id = self.Id;
    [self.navigationController pushViewController:localPlabsViewVc animated:YES];
}

#pragma mark - 查看全部商品的点击方法
-(void)footerButtonAction:(UIButton *)footerButton
{
    ShopTotalController *shopTotalViewVc = [[ShopTotalController alloc]initWithStyle:(UITableViewStylePlain)];
    shopTotalViewVc.Id = self.Id;
    [self.navigationController pushViewController:shopTotalViewVc animated:YES];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
